#!/bin/bash
#sar -n DEV -d -u -b 1 10000 

file=/tmp/$RANDOM
ncout=0
dcout=0
navg=0
navgc=0
davg=0
davgc=0
dtotal=0
ntotal=0

if [[ $1 == "record" ]]; then
    line=0
    echo -n "" > ./accdata/diskavgspeed.acc
    echo -n "" > ./accdata/netavgspeed.acc
    echo -n "" > ./accdata/disktotal.acc
    echo -n "" > ./accdata/nettotal.acc
    echo -n "" > ./accdata/diskcout.acc
    echo -n "" > ./accdata/netcout.acc
fi

while : ; do
    sar -n DEV -b 1 1 > $file
    echo -n -e "diskread : \t"
    disk=`cat $file | head -n 4 | tail -1 | awk '{print $6}'`
    disk=`echo "scale=3; $disk/2000.0" | bc` 
    echo -n -e "\t$disk MB/s \t"

    let "davgc=$davgc + 1";
    if [[ $davg == 0 ]]; then
        davg=$disk
        dtotal=$davg
    else 
        dtotal=`echo "scale=3; $dtotal+$disk" | bc`;
        davg=`echo "scale=3; $dtotal/$davgc" | bc`
    fi

    echo -n -e "net : \t"
    net=`cat $file | head -n 11 | tail -1 | awk '{print $7}'`
    net=`echo "scale=3; $net/1000.0" | bc` 
    echo -n -e "\t$net MB/s \t"

    let "navgc=$navgc + 1";
    if [[ $navg == 0 ]]; then
        navg=$net
        ntotal=$navg
    else 
        ntotal=`echo "scale=3; $ntotal+$net" | bc`;
        navg=`echo "scale=3; $ntotal/$navgc" | bc`
    fi 

    if [[ $disk > $net ]]; then
        let "dcout=$dcout + 1"
        echo -n -e "[ Disk ] $dcout\t"
    else
        let "ncout=$ncout + 1"
        echo -n -e "[ Net. ] $ncout\t"
    fi
    echo -e " diskavg =\t$davg netavg =\t$navg "

    if [[ $1 == "record" ]]; then
        echo "$line $davg" >> ./accdata/diskavgspeed.acc
        echo "$line $navg" >> ./accdata/netavgspeed.acc
        echo "$line $dtotal" >>./accdata/disktotal.acc
        echo "$line $ntotal" >>./accdata/nettotal.acc
        echo "$line $dcout " >> ./accdata/diskcout.acc
        echo "$line $ncout" >> ./accdata/netcout.acc
        let "line=$line+1"
    fi
done 

